import Vue from 'vue';
import axios from 'axios';
import config from '@/config/axios.conf';
import router from '@/router';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import notification from 'ant-design-vue/es/notification';

const request = axios.create(config);
var flag = true;

const requestErr = (error) => {
  notification.error({
    message: 'Error Notice',
    description: '请求错误,请检查网络!',
  });
  // notification.error({
  //   message: 'Error Notice',
  //   description: error.message,
  // });
  return Promise.reject(error);
};

// http request 拦截器
request.interceptors.request.use(
  (config) => {
    const token = Vue.ls.get(ACCESS_TOKEN);
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  }, requestErr,
);

// http response 拦截器
request.interceptors.response.use(
  (response) => {
    // console.log(response);
    if (response.data.errorcode === 405) {
      // 解决多次调用弹窗问题
      if (flag) {      
        flag = false;
        // token过期
        notification.error({
          message: 'Error Notice',
          description: '尚未登录或登录过期，请登录！',
        });
        Vue.ls.remove(ACCESS_TOKEN);
        router.replace({
          path: '/passport/login',
          // query: {
          //   redirect: router.currentRoute.fullPath,
          // },
        });
        setTimeout(() => {
          flag = true;
        }, 2000);
      }
    } else if(response.data.errorcode === 401) {
      console.log(response.data.messages);
      // notification.error({
      //   message: 'Error Notice',
      //   description: response.data.messages,
      // });
    }
    return response;
  }, requestErr,
);

export default request;
